var gateway = `ws://${window.location.hostname}:5765?id=kdl&key=76098491`;
var websocket;
window.addEventListener('load', onLoad);

function initWebSocket() {
	console.log('Trying to open a WebSocket connection...');
	websocket = new WebSocket(gateway);
	websocket.onopen = onOpen;
	websocket.onclose = onClose;
	websocket.onmessage = onMessage;
	websocket.onerror = onError;
}

function onError(event) {
	console.log("WebSocket Error:", event);
}

function onOpen(event) {
	console.log('Connection opened');
	document.getElementById('ws_status').innerHTML = "连接成功";
}

function onClose(event) {
	console.log('Connection closed');
	document.getElementById('ws_status').innerHTML = "连接关闭";
	//5秒后重联
	setTimeout(initWebSocket, 5000);
}

function onMessage(event) {
	console.log(event.data);
	if (isJSON(event.data)) {
		var data = JSON.parse(event.data);
		for (pin in data) {
			// 数字量控制块
			if (data[pin] == 1) {
				document.getElementById(pin).classList.remove("button_low");
			} else {
				if (document.getElementById(pin)) {
					document.getElementById(pin).classList.add("button_low");
				}
			}
			// 模拟量控制块
			var id_object = document.querySelector("#" + pin);
			if (id_object) {
				id_object.value = data[pin];
			}
		}
	}
}

function onLoad(event) {
	initWebSocket();
	initButton();
}

function isJSON(str) {
	if (!str) {
		return false;
	}
	if (typeof str == 'string') {
		try {
			var obj = JSON.parse(str);
			if (typeof obj == 'object' && obj) {
				return true;
			} else {
				return false;
			}
		} catch (e) {
			return false;
		}
	}
}

function initButton() {
	var digital_card = document.querySelectorAll(".digital-card");
	for (var i = 0; i < digital_card.length; i++) {
		var obj = digital_card[i].getElementsByTagName('button');
		for (var i = 0; i < obj.length; i++) {
			obj[i].addEventListener('click', btn_toggle);
		}
	}
}

function btn_toggle(e) {
	websocket.send(JSON.stringify({ "type": "digital", "id": e.target.id, "value": 0 }))
}

var heart = setInterval(function () {
	 websocket.send(JSON.stringify({"type":"heart"}));
	// console.log('heart');
},
	1000);

//一旦pwm数值发生变化，则发给服务端
var slideChange = (id, value) => {
	websocket.send(JSON.stringify({ "type": "pwm", "id": id, "value": value }));
}

//绑定max 和 min 的按钮
var pwm_card = document.querySelectorAll(".pwm-card");
for (var i = 0; i < pwm_card.length; i++) {
	var button = pwm_card[i].querySelectorAll("button");
	for (var n = 0; n < button.length; n++) {
		button[n].addEventListener('click', (e) => {
			var data = (e.target.id).split("-")
			var value = data[1] == 'max' ? 255 : 0;
			slideChange(data[0], value);
			document.getElementById(data[0]).value = value;

		})
	}
}
//绑定slide数值发生变化的事件
var slideData = document.querySelectorAll(".slide");
for (var i = 0; i < slideData.length; i++) {
	slideData[i].onchange = (e) => {
		slideChange(e.target.id, e.target.value);
	}
}
